package a.codetop;

import org.junit.Test;
import 其他.DataStructure.ListNode;

public class _6环形链表入口 {
    public ListNode detectCycle(ListNode head) {
        if(head == null) return null;

        ListNode fast = head, slow =head;
        boolean haveCircle = false;
        while(fast!= null && fast.next!=null) {
            slow = slow.next;
            fast = fast.next.next;
            if(fast == slow){
                haveCircle = true;
                break;
            }
        }

        //有环
        if(haveCircle){
            fast = head;
            while(fast!= slow){
                fast = fast.next;
                slow = slow.next;
            }
            return fast;
        }
        //无环
        return null;
    }

    @Test
    public void test(){
        /**
         *  1 2 3 4
         *    | _ |
         */
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l2;
        System.out.println("RES:" + detectCycle(l1).val);
    }
}
